package com.toptech.zsr.my;

import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.toptech.downloadmanager.DownloadClient;
import com.toptech.downloadmanager.DownloadConfigGuration;
import com.toptech.downloadmanager.FileInfo;
import com.toptech.downloadmanager.IRemoteService;
import com.toptech.downloadmanager.ToolUtils.ContantsUtils;
import com.toptech.downloadmanager.callback.ConnectServiceCallback;
import com.toptech.downloadmanager.callback.DownloadCallAdapter;
import com.toptech.zsr.my.recyclerview.MyRecyclerviewAdapter;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "zsr";
    private IRemoteService mBinder;
    private DownloadClient downloadClient;
    private RecyclerView mRecyclerView;
    private List<FileInfo> mDataList = new ArrayList<>();
    private MyRecyclerviewAdapter adapter;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);



        mRecyclerView = (RecyclerView) findViewById(R.id.recyclerview);

        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));

        downloadClient = DownloadClient.getInstance(this);

        downloadClient.connectServer(new ConnectServiceCallback() {



            @Override
            public void success() {

                Toast.makeText(MainActivity.this, "连接成功", Toast.LENGTH_SHORT).show();

                List<DownloadConfigGuration> configs = new ArrayList<DownloadConfigGuration>();

                DownloadConfigGuration config  = new DownloadConfigGuration.Builder()
                        .setName("为知笔记")
                        .setUrl("http://sw.bos.baidu.com/sw-search-sp/software/8b40925120bbf/wiznote_4.5.9.0.exe")
                        .setThreadCount(5)
                        .setPriority(ContantsUtils.PRIORITY_COMMON)
                        .build();

                DownloadConfigGuration config2 = new DownloadConfigGuration.Builder()
                        .setName("简书")
                        .setUrl("http://downloads.jianshu.io/apps/haruki/jianShu-release-2.1.3-JianShu.apk")
                        .setThreadCount(4)
                        .setPriority(ContantsUtils.PRIORITY_HIGHTEST)
                        .build();

                DownloadConfigGuration config3  = new DownloadConfigGuration.Builder()
                        .setName("聚美优品"+".apk")
                        .setUrl("http://apps.wandoujia.com/apps/com.jm.android.jumei/download")
                        .setThreadCount(5)
                        .setPriority(ContantsUtils.PRIORITY_COMMON)
                        .build();

                DownloadConfigGuration config4  = new DownloadConfigGuration.Builder()
                        .setName("今日头条"+".apk")
                        .setUrl(" http://gdown.baidu.com/data/wisegame/6b716369e081a648/jinritoutiao_604.apk")
                        .setThreadCount(5)
                        .setPriority(ContantsUtils.PRIORITY_COMMON)
                        .build();

                configs.add(config);
                configs.add(config2);
                configs.add(config3);
                configs.add(config4);


                Log.d(TAG, "success: "+downloadClient.getServerTaskNum());
               mDataList = downloadClient.addMulTasks(configs,ContantsUtils.GETNEEDDOWNLOADTASK);
               // mDataList = downloadClient.addNewTask(config3);
                downloadClient.startDownload(mDataList, new DownloadCallAdapter() {
                    @Override
                    public void getTaskInfoStatus(FileInfo fileInfo) {
                      //  Log.d(TAG, "getTaskInfoStatus: "+fileInfo.getFileName()+fileInfo.getProgress());
                        showTaskFileinfoToUI(fileInfo);
                    }

                    @Override
                    public void taskSuccess(FileInfo fileInfo) {
                        Toast.makeText(MainActivity.this, fileInfo.getFileName()+"下载成功", Toast.LENGTH_SHORT).show();
                        showTaskFileinfoToUI(fileInfo);
                    }

                    @Override
                    public void taskFail(int errorCode, String errorMsg, FileInfo fileInfo) {
                        if (fileInfo != null) {
                            try {
                                Button mButton = (Button) mRecyclerView.findViewWithTag(fileInfo.getApkurl()
                                        + ContantsUtils.TAG_FILEBTN);
                                if (errorCode == ContantsUtils.ERROR_HTTP){
                                    Toast.makeText(MainActivity.this, fileInfo.getFileName()+
                                            "  "+errorMsg, Toast.LENGTH_SHORT).show();

                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }

                });



                adapter = new MyRecyclerviewAdapter(MainActivity.this,
                        mDataList);

                mRecyclerView.setItemAnimator(new DefaultItemAnimator());

                mRecyclerView.setAdapter(adapter);


                adapter.setOnclickItemListener(new MyRecyclerviewAdapter.OnClickItemListener() {
                    @Override
                    public void setOnClickItemListener(View v, int position) {

                        Button mButton = (Button) v.findViewById(R.id.file_pause);
                        FileInfo fileInfo = mDataList.get(position);

                        if (downloadClient.isTaskPause(fileInfo)){
                            downloadClient.reStartTask(fileInfo);
                            mButton.setText("正在下载");
                        }else{
                            downloadClient.pauseTask(fileInfo);
                            mButton.setText("已暂停");
                        }

                        //Log.d(TAG, "setOnClickItemListener: "+mDataList.get(position).getId());


                    }

                    @Override
                    public void setonLongClickItemListener(View v, final int position) {
                        AlertDialog.Builder dialog = new AlertDialog.Builder(MainActivity.this);
                        dialog.setTitle("系统系统");
                        dialog.setMessage("是否删除该任务");
                        dialog.setCancelable(true);
                        final FileInfo fileinfo = mDataList.get(position);
                        Log.d(TAG, "setonLongClickItemListener: "+fileinfo.getFileName());
                        dialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Toast.makeText(MainActivity.this, "已删除", Toast.LENGTH_SHORT).show();


                                downloadClient.deleteTask(fileinfo);
                                mDataList.remove(position);
                                adapter.notifyItemRemoved(position);
                                adapter.notifyItemChanged(position);
                            }
                        });
                        dialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                               // Toast.makeText(MainActivity.this, "cancel", Toast.LENGTH_SHORT).show();
                            }
                        });

                        dialog.show();
                    }
                });

            }
            @Override
            public void fail() {
                Toast.makeText(MainActivity.this, "连接失败", Toast.LENGTH_SHORT).show();
            }
        });

    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main,menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        List<FileInfo> fileinfos = new ArrayList<>();
        switch(item.getItemId()){
            case R.id.menu_all_pause:
                Toast.makeText(this, "pauseAll", Toast.LENGTH_SHORT).show();
                fileinfos = downloadClient.pauseAllTask();
                for (FileInfo fileinfo : fileinfos){
                    if (fileinfo != null) {
                        Button mButton = (Button) mRecyclerView.findViewWithTag(fileinfo.getApkurl()
                                + ContantsUtils.TAG_FILEBTN);
                        mButton.setText("已暂停");
                    }

                }
                break;
            case R.id.menu_all_start:
                Toast.makeText(this, "reStartall", Toast.LENGTH_SHORT).show();
                fileinfos = downloadClient.reStartAllTask();
                for (FileInfo fileinfo : fileinfos){
                    if (fileinfo != null) {
                        Button mButton = (Button) mRecyclerView.findViewWithTag(fileinfo.getApkurl()
                                + ContantsUtils.TAG_FILEBTN);
                        mButton.setText("正在下载");
                    }

                }
                break;
        }
        return super.onOptionsItemSelected(item);
    }


    /**
     * 更新UI界面
     */
    int speedcount = 0;
    private void showTaskFileinfoToUI(FileInfo fileInfo){
        try {
            int progress = fileInfo.getProgress();
            ProgressBar seekbar = (ProgressBar) mRecyclerView.findViewWithTag(fileInfo.getApkurl()+ContantsUtils.TAG_PROGRESSBAR);
            TextView textProgress = (TextView)mRecyclerView.findViewWithTag(fileInfo.getApkurl()+ContantsUtils.TAG_TEXTPROGRESS);
            TextView textfilesize = (TextView)mRecyclerView.findViewWithTag(fileInfo.getApkurl()+ContantsUtils.TAG_FILESIZE);
            TextView textstatus = (TextView) mRecyclerView.findViewWithTag(fileInfo.getApkurl() + ContantsUtils.TAG_FILESTATUS);
            Button mButton = (Button) mRecyclerView.findViewWithTag(fileInfo.getApkurl()+ContantsUtils.TAG_FILEBTN);


            if (progress == 100){
                seekbar.setProgress(progress);
                textProgress.setVisibility(View.INVISIBLE);
                textfilesize.setVisibility(View.INVISIBLE);
                textstatus.setVisibility(View.INVISIBLE);
                mButton.setText("完成");
            }else{
                float speed = fileInfo.getSpeed();

                speedcount ++;
                if (speedcount >= 4){
                    speedcount = 0;
                    if (speed > 1024){
                        String speedString = getFloatToString(speed/1024);
                        textstatus.setText(speedString+"M/s");
                    }else{
                        String speedString  = getFloatToString(speed);
                        textstatus.setText(speedString+"kb/s");
                    }

                }


                seekbar.setProgress(progress);
                textProgress.setVisibility(View.VISIBLE);
                textProgress.setText(progress+"%");


                textfilesize.setVisibility(View.VISIBLE);


                String mCurProgress = fileInfo.getFiledownsize();
                String mProgressLength = fileInfo.getFilesize();
                textfilesize.setText(mCurProgress + "MB" + " / " + mProgressLength + "MB");
            }

        } catch (Exception e) {
            e.printStackTrace();
           // Log.d(TAG, "showTaskFileinfoToUIerror: "+e.toString());
        }

    }



    @Override
    protected void onDestroy() {
        downloadClient.unBinderServer();
        super.onDestroy();
    }


    private String getFloatToString(Float value){
        DecimalFormat decimalFormat =
                new DecimalFormat("0.00");//构造方法的字符格式这里如果小数不足2位,会以0补足.
        return  decimalFormat.format(value);
    }
}
